﻿//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;
var currentPopup = null;

var CreativeType =
{
    Image: 1,
    RichMedia: 2,
    TextLink: 3,
    Video: 4,
    Expandable: 5
}

//loading popup with jQuery magic!
function loadPopup(popup) {
    //Custom Code
    currentPopup = "#" + popup;
    //loads popup only if it is disabled	
    if (popupStatus == 0) {
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn(100);
        $(currentPopup).fadeIn(100);
        popupStatus = 1;
    }
}

function disablePopup() {
    if (popupStatus == 1) {
        $("#backgroundPopup").fadeOut(100);
        $(currentPopup).fadeOut(100);
        popupStatus = 0;
    }
}


//centering popup
function centerPopup(popup) {
    currentPopup = "#" + popup;
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $(currentPopup).height();
    var popupWidth = $(currentPopup).width();
    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {  // Explorer 6 Strict
        yScroll = document.documentElement.scrollTop;
    } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
    }
    var scrollTop = yScroll + windowHeight / 2 - popupHeight / 2
    $(currentPopup).css({
        //"position": "absolute",
        //"top": windowHeight / 2 - popupHeight / 2,
        //"left": windowWidth / 2 - popupWidth / 2
        "position": "absolute",
        "top": scrollTop,
        "left": windowWidth / 2 - popupWidth / 2

    });
    //only need force for IE6

    $("#backgroundPopup").css({
        "height": windowHeight
    });

}

window.onresize = function() {
    if (currentPopup != null)
        centerPopup(currentPopup.substring(1, currentPopup.length));
}

function centerPopupOverlay(popup) {
    var popupOverlay = "#" + popup;
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $(popupOverlay).height();
    var popupWidth = $(popupOverlay).width();
    var scrollTop = document.documentElement.scrollTop + 300;
    $(popupOverlay).css({
        "position": "absolute",
        "top": scrollTop,
        "left": windowWidth / 2 - popupWidth / 2
    });

}

function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}


//Function to Render the message along with the passed image and color on the avaliability of something    
function InsertErrorCheck(textboxName, message, image, color) {
    $("#validationMessage").html("");
    $("#validationMessage").html("<span id='message'></span>");
    $("#message").html("");
    $("#message").fadeIn(1, function() {
        var markup = "<img id='checkmark' src='App_Themes/Blue/img/" + image + "'/>";
        $('#message').append(markup);
        $("#message").css({ "color": color })
        $("#message").append(message);
    });
    $("#validationMessage").show();
}

//jQuery Ajax Processing Function
function ShowProgress(containers) {
    var containerArray = containers.split(',');
    var processing = "<img class='processing' src='App_Themes/jQGrid/img/ajax-loader-medium.gif' alt='Loadding.......' />";
    for (var i = 0; i < containerArray.length; i++) {
        $(containerArray[i]).html(processing);
        var marginLeft = $(containerArray[i]).width();
        var marginTop = $(containerArray[i]).height();
        var imageWidth = $('.processing').width();
        var imageHeight = $('.processing').height();
        $(containerArray[i] + ' .processing').css({ "margin-left": (marginLeft / 2) - (imageWidth / 2), "margin-top": marginTop / 2 - imageHeight / 2 });
    }
}

function ShowProgressAsync(containers, isLoaderImage, errMsg) {
    var containerArray = containers.split(',');

    var processing = "";
    var imageProcessing = '';
    if (isLoaderImage) {
        processing = "<div class='processingAsync' style='display:none'></div>";
        imageProcessing = "<div class='imageProcessingContainer'></div>";
    }
    else
        processing = "<span class='processingMsgAsync' style='display:none' >" + errMsg + "</span>";

    for (var i = 0; i < containerArray.length; i++) {
        var offset = $(containerArray[i]).offset();
        var offsetX = offset.left;
        var offsetY = offset.top;
        var divOffSetX = offsetX;
        var divOffSetY = offsetY;
        var length = $(containerArray[i]).width();
        var height = $(containerArray[i]).height();
        offsetX = offsetX + length / 2;
        offsetY = offsetY + height / 2;
        if (isLoaderImage)
            $(imageProcessing).insertAfter(containerArray[i]);
        $(processing).insertAfter(containerArray[i]);
        if (!isLoaderImage) {
            offsetX = offsetX / 2;
            $('.processing').css({ "position": "absolute", "display": "none", "left": offsetX, "top": offsetY, "z-index": "11" });
            $('.processingMsgAsync').css({ "position": "absolute", "display": "block", "width": length - offsetX, "left": offsetX, "top": offsetY, "z-index": "1" });
        }
        else {
            $('.processingAsync').css({ "position": "absolute", "display": "block", "left": offsetX, "top": offsetY, "z-index": "11" });
            $('.imageProcessingContainer').css({ "opacity": "0.1", "left": divOffSetX, "top": divOffSetY, "height": height, "width": length, "z-index": "10" });
        }
    }
}
function HideProgressAsync() {
    $('.processingAsync').fadeOut(1000, function() {
        $(this).remove();
    });
    $('.imageProcessingContainer').fadeOut(100, function() {
        $(this).remove();
    });

}
//jQuery Ajax Callback Functions
function ClientProxyDateFormatted(methodName, paramArray, successFunction, errorFunction) {
    var pagePath = window.location.pathname;
    var paramList = '';

    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '"' + ':' + '"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    var length = pagePath.length;
    if (pagePath.substring(length - 1, length) == "/") {
        pagePath += "Default.aspx";
    }
    else if (pagePath.substring(length - 5, length) != ".aspx") {
        pagePath += "/Default.aspx";
    }
    $.ajax({
        type: "POST",
        url: pagePath + "/" + methodName,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "text",
        processData: false,
        success: function(msgg) {
            var msg = JSON.parse(msgg, function(key, value) {
                var a;
                if (value != null) {
                    if (value.toString().indexOf('Date') >= 0) {
                        a = /^\/Date\((-?[0-9]+)\)\/$/.exec(value);
                        if (a) {
                            var dt = new Date(parseInt(a[1], 10));
                            return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
                        }
                    }
                    return value;
                }
            });
            successFunction(msg);
        },
        error: function(xhr, status, error) {
            errorFunction(xhr, status, error);
        }
    });
    return false;
}
function ClientProxy(methodName, paramArray, successFunction, errorFunction) {
    var pagePath = window.location.pathname;
    var paramList = '';

    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '"' + ':' + '"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    var length = pagePath.length;
    if (pagePath.substring(length - 1, length) == "/") {
        pagePath += "Default.aspx";
    }
    else if (pagePath.substring(length - 5, length) != ".aspx") {
        pagePath += "/Default.aspx";
    }

    $.ajax({
        type: "POST",
        url: pagePath + "/" + methodName,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "json",
        success: function(msg) {
            successFunction(msg);
        },
        error: function(xhr, status, error) {
            errorFunction(xhr, status, error);
        }

    });
    return false;
}

//Function for Enabling and Disabling the div's element when selected choice is use existing
//#region
function setDisabled(id, disabled) {
    if (!document.getElementById
|| !document.getElementsByTagName) return;
    var element = document.getElementById(id);
    if (disabled == true)
        $(element).css({ color: '#cccccc' });
    else
        $(element).css({ color: '#000000' });
    var nodesToDisable = { button: '', input: '', optgroup: '',
        option: '', select: '', textarea: ''
    };

    var node, nodes;
    var div = document.getElementById(id);
    if (!div) return;

    nodes = div.getElementsByTagName('*');
    if (!nodes) return;

    var i = nodes.length;
    while (i--) {
        node = nodes[i];
        if (node.nodeName
&& node.nodeName.toLowerCase() in nodesToDisable) {
            node.disabled = disabled;
        }
    }
}
//#endregion

//Function to trim the string
//#region

String.prototype.trim = function() {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
String.prototype.reduceLength = function() {
    return this.substring(1, 20) + '......';
}

//String.prototype.getUnique = function(array) {
function getUnique(array) {
    return uniqueArr(array); //Print the unique value
}
function uniqueArr(a) {
    temp = new Array();
    for (i = 0; i < a.length; i++) {
        if (!contains(temp, a[i])) {
            temp.length += 1;
            temp[temp.length - 1] = a[i];
        }
    }
    return temp;
}

//Will check for the Uniqueness
function contains(a, e) {
    for (j = 0; j < a.length; j++) if (a[j] == e) return true;
    return false;
}

function GetIndex(a, e) {
    for (j = 0; j < a.length; j++) if (a[j] == e) return j;
    return null;
}

//#endregion

//Function to check that whether an element exists in an array or not
//#region
Array.prototype.ContainsValue = function(value) {
    var arrayLength = this.length;
    for (var i = 0; i < arrayLength; i++) {
        if (this[i] === value)
            return true;
    }
    return false;
}
//#endregion


//Readin QueryString
function QueryString() {
    // PROPERTIES
    this.arg = new Array;
    this.status = false;

    // METHODS
    this.clear = Clear;
    this.get = Get;
    this.getAll = GetAll;
    this.getStatus = GetStatus;
    this.read = Read;
    this.set = Set;
    this.write = Write;

    // FUNCTIONS

    // Clears the array, this.arg, of all query string data
    function Clear() {
        this.arg = new Array;
    }

    // Returns a named value from the query string
    function Get(sName) {
        return this.arg[sName];
    }

    // Return all data as an associative array
    function GetAll() {
        return this.arg;
    }

    function GetStatus() {
        return this.status;
    }

    // Reads the query string into an array named this.arg
    function Read(sUrl) {
        var aArgsTemp, aTemp, sQuery;
        // You can pass in a URL query string
        if (sUrl) {
            sQuery = sUrl.substr(sUrl.lastIndexOf("?") + 1, sUrl.length);
        }
        // Or read it from the browser location
        else {
            sQuery = window.location.search.substr(1, window.location.search.length);
        }
        // Check that query string exists and contains data
        // If not (length < 1) then return
        if (sQuery.length < 1) { return; }
        // Else set this.status to true and proceed
        else { this.status = true; }
        //
        aArgsTemp = sQuery.split("&");
        for (var i = 0; i < aArgsTemp.length; i++) {
            aTemp = aArgsTemp[i].split("=");
            this.arg[aTemp[0]] = aTemp[1];
        }
    }

    // Overwrites an existing named value in the array, this.arg
    // You can also pass null to delete from array
    function Set(sName, sValue) {
        if (sValue == null) { delete this.arg[sName]; }
        else { this.arg[sName] = sValue; }
    }

    // Writes out a string from the data in this.arg array
    // This string can be used to pass a new query string to the browser
    // when navigating to the next page. This allows a page
    // to create and pass data to another page via JavaScript.
    function Write() {
        var sQuery = new String("");
        for (var sName in this.arg) {
            if (sQuery != "") { sQuery += "&"; }
            if (this.arg[sName]) { sQuery += sName + "=" + this.arg[sName]; }
        }
        if (sQuery.length > 0) { return "?" + sQuery; }
        else { return sQuery; }
    }
}

//-------------------------------------------------Code for implementing paging client side--------------------------//
var currPage = 1;
var numPerPage = 5;
var numPerPageCustomer = 10;
var pageCount = 1;
//---------------------------------Global variables for Customer profile paging--------------------------------------//
var currCustomerPage = 1;
var customerPageCount = 1;

//---------------------------------Global variables for Brand profile paging--------------------------------------//
var currBrandPage = 1;
var brandPageCount = 1;

//---------------------------------Global variables for audience profile paging--------------------------------------//
var currAudiencePage = 1;
var audiencePageCount = 1;

//---------------------------------Gloabal variable for buytype and pacing-------------------------------------------//
var pace = 1;
var buyType = 1;
var nullCustomerCheck = 0;

//--------------------------------General Event Handlers which are used globally-------------------------------------//
function ShowErrorMessage(message) {
    HideProgressAsync();
    var messageWrapper = '<div id="errorMessageContainer" class="popupOverlayMessage">' +
        '<span class="errorHeader"><a class="popupCloseSymbol"></a></span>' +
        '<div class="errorInformationContainer">' +
        '<span id="errorMessage"></span>' +
        '<br />' +
        '<input type="button" id="btnErrorOK" class="buttonCenter" />' +
        '</div>' +
        '<div class="backgroundPopupOverlay"></div>';
    $(messageWrapper).insertAfter('#aspnetForm');
    $('#errorMessage').html(message);
    centerPopupOverlay('errorMessageContainer');
    $("#backgroundPopupOverlay").css({
        "opacity": "0.1"
    });
    $("#backgroundPopupOverlay").fadeIn(100);
    //$(currentPopup).fadeIn(100);
    $('#errorMessageContainer').show();
    $('#errorMessageContainer')
        .bind('drag', function(event) {
            $(this).css({
                top: event.offsetY,
                left: event.offsetX
            });
        });
}
$('#btnErrorOK').live('click', function() {
    $('#errorMessageContainer').hide().remove();
});
$(".popupCloseSymbol").live('click',function() {
disablePopup(currentPopup);
$('#errorMessageContainer').hide().remove();
});
//Pass errorContainer as the already jQuery selector ready
//Pass checkBoxContainer as the simple id of the container in which we are searching for the empty checkboxes
function CheckEmptyCheckBoxes(errorContainer, checkBoxContainer) {
    var errorWrapper = $(errorContainer);
    var checkBoxWrapper = $('#' + checkBoxContainer + ' :checked');
    if (checkBoxWrapper.length == 0) {
        isValid = false;
        if (errorWrapper.children().is('label.error')) {
            if (!(errorWrapper.children($('label.error')).is(':visible'))) {
                errorWrapper.children($('label.error')).addClass('showError');
            }

        }
        else {
            $(errorWrapper).html("<label class='error'></label>");
            $(errorWrapper).find('label.error').addClass('showError');
        }

    }
    else if (checkBoxWrapper.length > 0) {
        $(errorWrapper).find('label.error').removeClass('showError');
    }
}

//Function to add validation and remove validation from the dropdownlist
function CheckValidationDropDownList(selector) {
    var tmpList = $(selector + ' :select');
    if (tmpList.val() == -1) {
        if ($(selector).next().is('label.error') && $(selector).next().is('label.error') != undefined) {
            if (!($(selector).next($('label.error')).is(':visible'))) {
                $(selector).next($('label.error')).addClass('showError');
            }

        }
        else {
            $("<label class='error'></label>").addClass('showError').insertAfter(selector);

        }
    }
    else {
        if ($(selector).next().is('label.error')) {
            ($(selector).next($('label.error'))).removeClass('showError');
        }
    }
}
function InsertErrorLabel(selector) {
    if ($(selector).attr('type') == 'text') {
        if ($(selector).val().trim() == '') {
            if ($(selector).is(':visible')) {
                isValid = false;
                if ($(selector).next().is('label.error')) {
                    if (!($(selector).next($('label.error')).is(':visible'))) {
                        $(selector).next($('label.error')).addClass('showError');
                    }

                }
                else {
                    $("<label class='error'></label>").addClass('showError').insertAfter($(selector));

                }
            }
        }
    }
}

function LoadNavigation(tabId) {
    switch (tabId) {
        case '1':
            $('#tabnav li').eq(0).addClass('selected');
            return;
        case '2':
            $('#tabnav li').eq(1).addClass('selected');
            return;
        case '3':
            $('#tabnav li').eq(2).addClass('selected');
            return;
        case '4':
            $('#tabnav li').eq(3).addClass('selected');
            return;
        case '5':
            $('#tabnav li').eq(4).addClass('selected');
            return;
    }
}